$(function () {
    getMenu();
    initTabs();
    setPermissions();
    $(document).find('head').append(`<link rel="stylesheet" href="css/home.css?rand=${Math.random()}"/>`);
    addNavigationPage();
})

/**
 * 清空权限
 */
function clearPermissions() {
    localStorage.clear();
}

/**
 * 获取权限
 */
function setPermissions() {
    const KEY = "XZY_USER_PERMISSIONS";
    if (localStorage.getItem(KEY) == undefined) {
        $.ajax({
            url: 'sysUser/permissions',
            method: 'GET',
            dataType: 'json',
            success: function (data) {
                localStorage.setItem(KEY, JSON.stringify(data || []));
            }
        });
    }
}

/**
 * 获取权限
 */
function getPermissions() {
    const KEY = "XZY_USER_PERMISSIONS";
    return JSON.parse(localStorage.getItem(KEY));
}

/**
 * 初始化标签页
 */
function initTabs() {
    $('#home_tabs').tabs({
        fit: true,
        border: false,
        onContextMenu: function (e, title, index) {
            e.preventDefault();
            let div = `<div id="home_tabs_menu">
                <div data-options="iconCls:'icon-reload'">刷新当前</div>
                <div data-options="iconCls:'icon-application_delete'">关闭当前</div>
                <div data-options="iconCls:'icon-application_form_delete'">关闭所有</div>
                <div data-options="iconCls:'icon-no'">关闭其他</div>
                <div data-options="iconCls:'icon-arrow_left'">关闭左侧标签页</div>
                <div data-options="iconCls:'icon-arrow_right'">关闭右侧标签页</div>
                </div>`;
            if ($("#home_tabs_menu").length <= 0) $('body').append(div);
            let menu = $("#home_tabs_menu");
            menu.menu({
                border: false,
                onClick: function (item) {
                    let name = item.text;
                    tabContextMenu($('#home_tabs'), name, title, index);
                }
            });
            menu.menu('show', {
                top: e.pageY,
                left: e.pageX
            });
        },
    });
}

/**
 * 增加导航页面
 */
function addNavigationPage() {
    const NAVIGATION_PAGE_TITLE = "导航";
    /*if ($('#home_tabs').tabs('exists', NAVIGATION_PAGE_TITLE)) {
        let navPageTab = $('#home_tabs').tabs('getTab', NAVIGATION_PAGE_TITLE);
        refreshTab(navPageTab);
        $('#home_tabs').tabs('select', NAVIGATION_PAGE_TITLE);
    } else {*/
    $('#home_tabs').tabs('add', {
        title: NAVIGATION_PAGE_TITLE,
        closable: false,
        fit: true,
        content: createIFrame("navigate"),
        tools: [{
            iconCls: 'icon-help',
            handler: function () {
            }
        }]
    })
    // }
}

/**
 * 标签页操作菜单
 */
function tabContextMenu(ele, name, title, index) {
    let tabs = $(ele);
    switch (name) {
        case '关闭当前':
            tabs.tabs('close', title);
            break;
        case '刷新当前':
            tabs.tabs('select', title);
            let currentTab = tabs.tabs('getSelected');
            refreshTab(currentTab);
            break;
        case '关闭所有':
            $(".tabs li").each(function (index, obj) {
                let tabTitle = $(".tabs-closable", this).text();
                tabs.tabs("close", tabTitle);
            });
            break;
        case '关闭其他':
            $(".tabs li").each(function (index, obj) {
                let tabTitle = $(".tabs-closable", this).text();
                if (title != tabTitle) {
                    tabs.tabs("close", tabTitle);
                }
            });
            break;
        case '关闭左侧标签页':
            var $tabs = $(".tabs li");
            for (let i = 0; i < $tabs.length; i++) {
                //获取所有可关闭的选项卡
                let tabTitle = $(".tabs-closable", $tabs[i]).text();
                if (tabTitle != title) {
                    tabs.tabs("close", tabTitle);
                } else {
                    break;
                }
            }
            break;
        case '关闭右侧标签页':
            var $tabs = $(".tabs li");
            for (let i = $tabs.length - 1; i >= 0; i--) {
                //获取所有可关闭的选项卡
                let tabTitle = $(".tabs-closable", $tabs[i]).text();
                if (tabTitle != title) {
                    tabs.tabs("close", tabTitle);
                } else {
                    break;
                }
            }
            break;
    }
}

/**
 * 刷新
 * @param currentTab
 */
function refreshTab(currentTab) {
    if (!currentTab) currentTab = $(ele).tabs('getSelected');
    if (currentTab && currentTab.find('iframe').length > 0) {
        currentTab.find('iframe')[0].contentWindow.location.reload(true);
    }
}

function a(id) {
    $.post('sysUserVisitList/insertSelective', {
        sysMenuId: id,
    }, function (data) {
        $.messager.show({title: '提示', msg: data.message});
        refreshNavigatePage();
    }, 'json');
}

function b(id) {
    $.post('sysUserVisitList/deleteByMenuId', {
        id: id,
    }, function (data) {
        $.messager.show({title: '提示', msg: data.message});
        refreshNavigatePage();
    }, 'json');
}

/**
 * 生成菜单Tree
 */
function getMenu() {
    $('#home_tree').ejectAside({
        url: 'sysMenu/tree',
        menuSplitSize: 6,
        labelWidth: 150,
        onLoadFilter: function (data = []) {
            for (let i = 0; i < data.length; i++) {
                if (i === 0) {
                    data[i]['childItemNumberPerCol'] = 4;
                    break;
                }
            }
            return data;
        },
        onClickChild: function (id, node) {
            let attr = $(node).data('options');
            addTab(attr.text, attr.attribute.path);
        },
        backgroundColor: '#364150',
        onContextmenuChild(id, node, e) {
            // 右击事件
            e.preventDefault();
            if (id != undefined) {
                let menu = $(`<div class="easyui-menu">
                                   <div data-options="iconCls:'icon-add',">添加常用</div>
                                   <div data-options="iconCls:'icon-cancel',">取消常用</div>
                              </div>`);
                menu.menu({
                    onHide: function () {
                        $(this).menu('destroy');
                    }
                });
                $(node).append(menu);
                let y = $(node).parent().parent().offset().top;
                let x = $(node).parent().parent().offset().left;
                menu.menu('show', {
                    top: e.pageY - y,
                    left: e.pageX - x
                });
                menu.find('div[class="menu-text"]').each(function () {
                    $(this).click(function () {
                        if ($(this).html() == '添加常用') {
                            a(id);
                        } else {
                            b(id);
                        }
                    })
                })
            }
        },
    })
}

/**
 * 刷新导航页面
 */
function refreshNavigatePage() {
    let navTab = $('#home_tabs').tabs('getTab', 0);
    if (navTab) {
        refreshTab(navTab);
    }
}

/**
 * 登出
 */
function btn_logout() {
    $.messager.confirm('提示', '是否登出？', function (r) {
        if (r) {
            $.ajax({
                url: 'system/logout',
                type: 'POST',
                dataType: 'json',
                complete: function (xhr, status) {
                    clearPermissions();
                    window.location.reload();
                }
            })
        }
    })
}

/**
 * 创建iFrame
 * @param url
 * @returns {string}
 */
function createIFrame(url) {
    return `<iframe scrolling="auto" frameborder="0" src="${url}" style="width:100%;height:100%;overflow:hidden;"/>`;
}

/**
 * 新增标签页
 * @param title
 * @param url
 * @param iconCls
 */
function addTab(title, url, iconCls) {
    if ($('#home_tabs').tabs('exists', title)) {
        $('#home_tabs').tabs('select', title);
    } else {
        $('#home_tabs').tabs('add', {
            title: title,
            fit: true,
            content: createIFrame(url),
            closable: true,
            iconCls: iconCls || ''
        });
        $('#home_tabs').find('div > .panel-body').addClass('overflow-hidden');
    }
}

/**
 * 重命名标题(添加后缀)
 * @param id
 */
function renameTab(id) {
    let tab = $('#home_tabs').tabs('getSelected');
    let index = $('#home_tabs').tabs('getTabIndex', tab);
    if (index != -1) {
        let currentTitle = tab.panel('options').title || '';
        let arr = currentTitle.split('-');
        let newTitle = id ? (arr[0] + '-' + id) : arr[0];
        tab.panel('setTitle', newTitle);
    }
}

/**
 * 获取当前标签名
 */
function getSelectedTabOptions() {
    let selected = $('#home_tabs').tabs('getSelected');
    return $(selected).panel('options');
}

/**
 * 关闭标签页
 */
function closeTab() {
    let tab = $("#home_tabs").tabs('getSelected');
    let index = $("#home_tabs").tabs('getTabIndex', tab);
    $("#home_tabs").tabs('close', index);
}

/**
 * 修改密码
 */
function btn_modify_pwd() {
    $('#modifyPwd').dialog('open');
}

/**
 * 取消
 */
function btn_modify_pwd_dialog_cancel() {
    $('#modifyPwd').dialog('close');
}

/**
 * 扫码关注
 */
function btn_focus() {
    let btn = $(this);
    btn.linkbutton('disable');
    $.ajax({
        url: 'userMill/getFocusQrURL',
        type: 'POST',
        dataType: 'json',
        success: function (data) {
            if (data.success) {
                let div = $(`
                    <div>
                        <div class="easyui-dialog" 
                        data-options="title:'扫码关注',width:400,height:400,modal:true,
                                      resizable:false,border:false,onClose:function(){
                                              $(this).dialog('destroy');
                        }">
                        <input style="width: 99%;height: 99%" type="image" alt="暂无二维码" src="${data.data}">
                        </div>
                    </div>`);
                $('body').append(div);
                $.parser.parse(div);
            }
        },
        complete: function () {
            btn.linkbutton('enable');
        }
    });
}

/**
 * 保存
 */
function btn_modify_pwd_form_save() {
    $('#modifyPwd').find('form').eq(0).form('submit', {
        url: 'sysUser/password/edit',
        onSubmit: function (param) {
            return $(this).form('validate');
        },
        success: function (data) {
            if (!data) {
                return;
            }
            data = eval('(' + data + ')');
            if (data.success) {
                $('#modifyPwd').dialog('close');
                $.messager.show({title: '提示', msg: data.message});
            } else {
                $.messager.alert('提示', data.message, 'warning');
            }
        }
    })
}

$.extend($.fn.validatebox.defaults.rules, {
    equals: {
        validator: function (value, param) {
            let _value = $(param[0]).textbox('getValue');
            return value == _value;
        },
        message: '两次密码输入不正确!'
    }
});